//阻塞队列的模拟实现
class  BlockingQueue {
    int[] queue = new int[3];
    int prev = 0;
    int tail = 0;
    int size = 0;
    Object lock=new Object();
    //入队列
    public void put (int value) throws InterruptedException {
        //判断队列是否为满
        synchronized (lock) {
            if (size >= queue.length) {
                lock.wait();
            }
            queue[tail] = value;
            size++;
            tail++;
            if (tail >= queue.length) {
                tail = 0;
            }
            //此处唤醒put队列为空的阻塞等待
            lock.notify();
        }
    }
    public Integer take() throws InterruptedException {
        //判断队列是否为空
        synchronized (lock) {
            if (size == 0) {
                lock.wait();
            }
            int val = queue[prev];
            prev++;
            size--;
            if (prev >= queue.length) {
                prev = 0;
            }
            lock.notify();//此处唤醒put队列未满的阻塞队列
            return val;
        }
    }
}
public class ThreadDemo3 {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue=new BlockingQueue();
        //生产者
        Thread t=new Thread(()->{
            int num=0;
            while(true){
                try {
                    System.out.println("生产了"+num);
                    blockingQueue.put(num);
                    num++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t1=new Thread(()->{
            try {
                while(true) {
                    int num = blockingQueue.take();
                    System.out.println("消费了" + num);
                    Thread.sleep(30);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.start();
        t1.start();
    }

}
